import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

export function objToBlank(obj) {
  const resObj = {}
  for (const key in obj) {
    if (typeof obj[key] === 'string') {
      resObj[key] = obj[key].replace(/\s*/g, '')
    } else {
      resObj[key] = obj[key]
    }
  }
  return resObj
}
export function getNowDate() {
  const date = new Date()
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  let strDate = date.getDate()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  return year + '年' + month + '月' + strDate + '日'
}

export function getDate(value) {
  const date = new Date(value)
  const y = date.getFullYear()
  let MM = date.getMonth() + 1
  MM = MM < 10 ? ('0' + MM) : MM
  let d = date.getDate()
  d = d < 10 ? ('0' + d) : d
  return y + '年' + MM + '月' + d + '日'
}

export function exportPDF(elName, fileName) {
  const element = document.getElementById(elName)
  html2Canvas(element, {
    logging: false,
    dpi: 144,
    scale: 2
  }).then(function(canvas) {
    const pdf = new JsPDF('p', 'mm', 'a4')
    const ctx = canvas.getContext('2d')
    const a4w = 170
    const a4h = 257
    const imgHeight = Math.floor(a4h * canvas.width / a4w)
    let renderedHeight = 0
    while (renderedHeight < canvas.height) {
      const page = document.createElement('canvas')
      page.width = canvas.width
      page.height = Math.min(imgHeight, canvas.height - renderedHeight)

      page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
      pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'PEG', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width))

      renderedHeight += imgHeight
      if (renderedHeight < canvas.height) {
        pdf.addPage()
      }
    }
    pdf.save(fileName)
  })
}
